package com.lifesea.notify.biz;

import com.lifesea.commons.exception.ErrorCodeConst;
import com.lifesea.commons.exception.ErrorCodeException;
import com.lifesea.commons.utils.CheckUtils;
import com.lifesea.model.NotifyTemplate;
import com.lifesea.model.dto.AppPushRequest;
import com.lifesea.notify.service.IPushService;
import com.lifesea.notify.service.NotifyTemplateService;
import com.lifesea.notify.utils.FreemarkerUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * APP消息推送业务处理类
 * Created by iscdw on 2016/4/26.
 */
@Service
public class PushBiz {

    private static final Logger logger = LoggerFactory.getLogger(PushBiz.class);

    @Autowired
    private NotifyTemplateService notifyTemplateService;

    /**
     * 推送接口,需要根据接口生成实现
     */
    @Autowired
    private IPushService pushService;

    public void pushByTemplate(AppPushRequest templateRequest) {
        CheckUtils.check(templateRequest.getTemplateType(), "templateType");
        String content = null;
        NotifyTemplate notifyTemplate = notifyTemplateService.get(templateRequest.getTemplateType());
        if (templateRequest.getFormatObj() != null) {
            try {
                content = FreemarkerUtils.format(notifyTemplate.getTemplateText(), templateRequest.getFormatObj());
            } catch (Exception e) {
                logger.error("向APP推送消息时填充模板出错", e);
                throw new ErrorCodeException(ErrorCodeConst.GLOBAL_SYS_UNKNOW, "向APP推送消息时填充模板出错");
            }
        } else {
            content = notifyTemplate.getTemplateText();
        }
        templateRequest.setContent(content);

        pushService.push(templateRequest);
    }

    public void push(AppPushRequest request) {
        logger.info("content:{}", request.getContent());
        if (StringUtils.isNotEmpty(request.getContent())) {
            pushService.push(request);
        } else {
            pushByTemplate(request);
        }
    }

}
